package com.sh.healthtv.ui;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;

import com.sh.healthtv.R;
import com.sh.healthtv.app.AppContext;
import com.sh.healthtv.app.com.sh.healthtv.obserservice.HisColObserveble;
import com.sh.healthtv.app.com.sh.healthtv.obserservice.HisColObserver;
import com.sh.healthtv.app.com.sh.healthtv.obserservice.PlayObserveble;
import com.sh.healthtv.app.com.sh.healthtv.obserservice.PlayObserver;
import com.sh.healthtv.base.BaseActivity;
import com.sh.healthtv.config.Constant;
import com.sh.healthtv.database.LitepalTVCollectUitils;
import com.sh.healthtv.database.LitepalTVHtoryUitils;
import com.sh.healthtv.database.model.CollectionProgram;
import com.sh.healthtv.database.model.HistoryProgram;
import com.sh.healthtv.net.entity.Epg;
import com.sh.healthtv.tencent.SonicSessionClientImpl;
import com.sh.healthtv.webconfig.ActivityFunc;
import com.sh.healthtv.webconfig.KnowledgeJs;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class MainActivity extends BaseActivity implements PlayObserver, HisColObserver {
    private String TAG = "MainActivity";
    private WebView webView;
    long time1, time2, time3;
    //    private String url = "http://192.168.1.220:8020/showtv0414/%E9%99%84%E8%BF%91%E6%99%AF%E7%82%B9_%E4%BA%BA%E6%96%87%E6%99%AF%E8%A7%82.html";
    private String url1 = "file:///android_asset/healthca/healthtv/index.html";
    private String url12 = "file:///android_asset/healthca/healthca/healthTV/index.html";
    private SonicSessionClientImpl sonicSessionClient = null;
   // private SonicSession sonicSession;

    private String url4 = "http://192.168.1.238:8085/static/healthtv/index.html#/";
    private ImageView page_ad;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //initSonic();
        // 隐藏标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
//        SQLiteDatabase data = Connector.getDatabase();
//        showdata();
        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

       // Toast.makeText(this, url1, Toast.LENGTH_LONG).show();
        init();

    }

    private void init() {

        PlayObserveble.getInstance().registerObserver(this);
        HisColObserveble.getInstance().registerObserver(this);
        page_ad = (ImageView) findViewById(R.id.page_ad);
        webView = (WebView) findViewById(R.id.helpfeedback_wv);
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        WebSettings webSettings = webView.getSettings();
        // webView.clearCache(true);
        if (Build.VERSION.SDK_INT > 17) {
            webSettings.setMediaPlaybackRequiresUserGesture(false);//不需要请求控制直接播放媒体文件
        }
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setJavaScriptEnabled(true);
//        webSettings.setSupportMultipleWindows(true);// 新加
        webSettings.setBuiltInZoomControls(true);// 隐藏缩放按钮
//        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// 排版适应屏幕
        //使用localStorage则必须打开
        webSettings.setGeolocationEnabled(true);
        webSettings.setDomStorageEnabled(true); //兼容jw
//        String dbPath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
//        webSettings.setDatabasePath(dbPath);
        webSettings.setDatabaseEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);

//        webSettings.setAppCacheMaxSize(1024 * 1024 * 2);//设置缓冲大小，我设的是8M
//        String appCacheDir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
//        webSettings.setAppCachePath(appCacheDir);
//        webSettings.setAppCacheEnabled(true);
//        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
//        webView.setWebChromeClient(new MyChromeViewClient());
        webSettings.setAppCacheMaxSize(1024 * 1024 * 2);//设置缓冲大小，我设的是8M
        String appCacheDir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
        webSettings.setAppCachePath(appCacheDir);
        webSettings.setAppCacheEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        ActivityFunc func = new KnowledgeJs(this);
        webView.removeJavascriptInterface("searchBoxJavaBridge_");
        webView.addJavascriptInterface(func, "ActivityFunc");
        webView.loadUrl(url1);
        time1 = new Date().getTime();
        webView.setWebViewClient(new WebViewClient() { //腾讯内核缓存

            @TargetApi(21)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return shouldInterceptRequest(view, request.getUrl().toString());
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
//                if (sonicSession != null) {
//                    return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url);
//                }
                return null;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                time2 = new java.util.Date().getTime();
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                time3 = new java.util.Date().getTime();
              //  page_ad.setVisibility(View.GONE);
                Log.i(TAG, "onPageFinished: " + time1);
                Log.i(TAG, "onPageFinished: " + time2);
                Log.i(TAG, "onPageFinished: " + time3);
                Log.i(TAG, "onPageFinished: " + (time2 - time1));
                Log.i(TAG, "onPageFinished: " + (time3 - time2));
                Log.i(TAG, "onPageFinished: " + (time3 - time1));
//                if (sonicSession != null) {
//                    sonicSession.getSessionClient().pageFinish(url);
//                }
                super.onPageFinished(view, url);
            }
        });
        // webview is ready now, just tell session client to bind
//        if (sonicSessionClient != null) {
//            sonicSessionClient.bindWebView(webView);
//            sonicSessionClient.clientReady();
//        } else { // default mode
           // webView.loadUrl(url4);
       // }
        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_UP) {

                }
                return false;
            }
        });


    }

    //初始化腾讯内核插件
   // private void initSonic() {
     //   SonicSessionConfig.Builder sessionConfigBuilder = new SonicSessionConfig.Builder();
    //    sonicSession = SonicEngine.getInstance().createSession(url4, sessionConfigBuilder.build());
//        if (null != sonicSession) {
//            sonicSession.bindClient(sonicSessionClient = new SonicSessionClientImpl());
//        } else {
            // this only happen when a same sonic session is already running,
            // u can comment following codes to feedback as a default mode.
       //     throw new UnknownError("create session fail!");
       // }
  //  }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        int key = event.getKeyCode();
        if (key == Constant.Control_KEYCODE_EXIT) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                Log.i(TAG, "goBack: " + key);
                webView.loadUrl("javascript:goBack()");
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void connectProgram(int type) {
        CollectionProgram cp = new CollectionProgram();
        Epg epg = AppContext.getCURRENTEPG();
        cp.setName(epg.getName());
        cp.setCollectDate(getTime());
        cp.setImageUrl(epg.getImageUrl());
        if ("1".equals(epg.getIsBeenCollect())) {
            int s = LitepalTVCollectUitils.deleteTVCollect(epg.getUseid());
            Log.i(TAG, "connectProgram: 已经被收藏删除" + s);
        } else {
            cp.setUseId(epg.getUseid());
            List<CollectionProgram> list = LitepalTVCollectUitils.queryAllTVCollect();
            if (list.size() >= 3) {
                int del = LitepalTVCollectUitils.deleteTVCollect(list.get(2).getUseId());
                Log.i(TAG, "connectProgram: 超过12个删除最后一个" + del);
            }
            boolean b = LitepalTVCollectUitils.insertTVCollect(cp);
            Log.i(TAG, "connectProgram: 没有被收藏直接加入" + b);
        }
        showdata();
    }

    @Override
    public void programHis(int time, int type) {
        HistoryProgram p = new HistoryProgram();
        Epg epg = AppContext.getCURRENTEPG();
        p.setImageUrl(epg.getImageUrl());
        p.setName(epg.getName());
        p.setPlayDate(getTime());
        p.setPlayState(type + "");
        p.setPlayTime(time + "");
        if (1 == epg.getHisPlayed()) {
            int his = LitepalTVHtoryUitils.updataTVHtory(p, epg.getUseid());
            Log.i(TAG, "programHis: 历史更新完成" + his);
        } else {
            p.setUseId(epg.getUseid());
            List<HistoryProgram> list = LitepalTVHtoryUitils.queryAllTVHtory();
            if (list.size() >= 3) {
                int del = LitepalTVHtoryUitils.deleteTVHtory(list.get(2).getUseId());
                Log.i(TAG, "programHis: 超过12个删除最后一个" + del);
            }
            boolean b = LitepalTVHtoryUitils.insertTVHtory(p);
            Log.i(TAG, "programHis: 没有看过直接加入" + b);
        }

        showdata();
    }

    private void showdata() {
        Log.i(TAG, "当前收藏数量: " + LitepalTVCollectUitils.queryAllTVCollect().size());
        Log.i(TAG, "当前播放历史记录: " + LitepalTVHtoryUitils.queryAllTVHtory().size());
    }

    private String getTime() {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd  hh:mm:ss");
        return sDateFormat.format(new java.util.Date());
    }

    @Override
    protected void onDestroy() {
//        if (null != sonicSession) {
//            sonicSession.destroy();
//            sonicSession = null;
//        }
        PlayObserveble.getInstance().unregisterObserver(this);
        HisColObserveble.getInstance().unregisterObserver(this);
        super.onDestroy();
    }

    @Override
    public void getHisList(final List<HistoryProgram> list) {
        Log.i(TAG, "getHisList: " + list);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    webView.loadUrl("javascript:reHisList('" + HistoryProgramIn2Json(list) + "')");
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i(TAG, "getHisList: 查询历史异常");
                }
            }
        });
    }

    @Override
    public void getColList(final List<CollectionProgram> list) {
        Log.i(TAG, "getColList: " + list);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    webView.loadUrl("javascript:reColList('" + CollectionProgram(list) + "')");
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i(TAG, "getHisList: 查询收藏异常");
                }
            }
        });

    }

    public static String HistoryProgramIn2Json(List<HistoryProgram> items) throws JSONException {
        if (items == null) return "[]";
        JSONArray array = new JSONArray();
        JSONObject jsonObject = null;
        HistoryProgram info = null;
        for (int i = 0; i < items.size(); i++) {
            info = items.get(i);
            jsonObject = new JSONObject();
            jsonObject.put("useId", info.getUseId());
            jsonObject.put("name", info.getName());
            jsonObject.put("imageUrl", info.getImageUrl());
            jsonObject.put("playDate", info.getPlayDate());
            jsonObject.put("playTime", info.getPlayTime());
            jsonObject.put("playState", info.getPlayState());
            array.put(jsonObject);
        }
        return array.toString();
    }

    public static String CollectionProgram(List<CollectionProgram> items) throws JSONException {
        if (items == null) return "[]";
        JSONArray array = new JSONArray();
        JSONObject jsonObject = null;
        CollectionProgram info = null;
        for (int i = 0; i < items.size(); i++) {
            info = items.get(i);
            jsonObject = new JSONObject();
            jsonObject.put("useId", info.getUseId());
            jsonObject.put("name", info.getName());
            jsonObject.put("imageUrl", info.getImageUrl());
            jsonObject.put("collectDate", info.getCollectDate());
            array.put(jsonObject);
        }
        return array.toString();
    }

    @Override
    protected void onResume() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    webView.loadUrl("javascript:reColList('" + CollectionProgram(LitepalTVCollectUitils.queryAllTVCollect()) + "')");
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i(TAG, "getHisList: 查询收藏异常");
                }
            }
        });
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    webView.loadUrl("javascript:reHisList('" + HistoryProgramIn2Json(LitepalTVHtoryUitils.queryAllTVHtory()) + "')");
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i(TAG, "getHisList: 查询历史异常");
                }
            }
        });


        super.onResume();
    }




}

//
//class MyChromeViewClient extends WebChromeClient {
//    //重写这个方法就OK 了
//    @Override
//    public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota, long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
//        //设置数据库存储大小
//        quotaUpdater.updateQuota(estimatedSize * 1);
//    }
//
//    //扩充缓存的容量
//    @Override
//    public void onReachedMaxAppCacheSize(long spaceNeeded,
//                                         long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
//        quotaUpdater.updateQuota(spaceNeeded * 2);
//    }
//
//
//}